<?php
class NaiveBayesClassifier {
	private $index = array();
	private $classes = array('pos', 'neg');
	private $classNbTokens = array('pos' => 0, 'neg' => 0);
	private $nbToken = 0;
	private $nbSentencesByClass = array('pos' => 0, 'neg' => 0);
	private $nbTotalSentences = 0;
	private $documentPos;
	private $documentNeg;
	
	public function __construct() {
		$this -> addDocument('./src/rt-polarity.pos', 'pos');
		$this -> addDocument('./src/rt-polarity.neg', 'neg');				
	}
			
	public function addDocument($file, $class, $limit = 0) {
		$fh = fopen($file, 'r');
		$i = 0;
		/* If the classe in the input of the function does not exist in the array $classes of the class */
		if(!in_array($class, $this->classes)) {
				echo "Invalid class specified\n";
				return;
		}
		while($line = fgets($fh)) {
			if($limit > 0 && $i > $limit) {
					break;
			}
			$i++;
			
			/* We update the total number of sentences in our training set */
			$this->nbTotalSentences++;
			/* We update the number of sentences depending on the class of the file*/
			$this->nbSentencesByClass[$class]++;
			/* we get every words of sentences in an array */
			$tokens = $this->tokenise($line);
			foreach($tokens as $token) {
					/* if the token does not exist, we set it to 0 it will be set to 1 just after */
					if(!isset($this->index[$token][$class])) {
							$this->index[$token][$class] = 0;
					}
					/* We update the frequency of this token */
					$this->index[$token][$class]++;
					/* We update the number of token in the class */
					$this->classNbTokens[$class]++;
					$this->nbToken++;
			}
		}
		fclose($fh);
	}
   
	public function classify($tokens) {
		$classScores = array();
		/* for each class : pos and neg */
		foreach($this -> classes as $class) {
			/* We firstly set the score of the class to 1 */
			$classScores[$class] = 1;
			/* For each tokens in the document */
			foreach($tokens as $token) {
				/* If the token exist in the index of this class,
					we set $$count to the frewuency of this item */
				if (isset($this->index[$token][$class]))
					$count = $this->index[$token][$class];
				else
					$count = 0;
				/* We compute and update the core of each class :
					$count : frequency of the token we are studying in the training set
					$this->classNbTokens[$class] : number of token for the class of the training set
					$this->nbToken : total number of tokens in all the training set
				*/
				$classScores[$class] = $classScores[$class] * (($count + 1) / ($this->classNbTokens[$class] + $this->nbToken));								
				}
		}
		arsort($classScores);
		/* We return the name of the class(pos or neg) that has the higher final score */
		return key($classScores);
	}
	
	/* return every words in an array */
	private function tokenise($sentence) {
		$sentence = strtolower($sentence);
		preg_match_all('/\w+/', $sentence, $matches);
		return $matches[0];
	}
}

?>